package com.itheima.security;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;


import java.util.*;

/*想要对菜单进行权限控制的话,先要确定该用户具有哪些权限
* 可以使用哪些菜单
* 根据用户查询出角色,根据角色查寻出所拥有的菜单
* List<Menu> list*/
/*
 *@AUTHOR:LIUCHAO;
 *@DATE: 2020/9/18 10:20
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;/*passwordEncoder.encode()使用bcrypt提供的方法对密码进行加密*/
@Reference //注意：此处要通过dubbo远程调用用户服务
private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("username = " + username);

        com.itheima.pojo.User user= userService.findPasswordByName(username);
        System.out.println(user.getPassword()+user.getUsername());
          if (user==null){
              return null;
          }

        ArrayList<GrantedAuthority> list = new ArrayList<>();
        //将用户信息返回给框架
        //框架会进行密码比对(页面提交的密码和数据库中查询的密码进行比对)
     /*   if(username.equals("liuchao")){
            list.add(new SimpleGrantedAuthority("CHECKITEM_ADD"));//授权  //权限
            list.add(new SimpleGrantedAuthority("CHECKITEM_QUERY"));//授权  //权限
            list.add(new SimpleGrantedAuthority("CHECKITEM_DELETE"));//授权  //权限
            list.add(new SimpleGrantedAuthority("CHECKITEM_UPDATE"));//授权  //权限
        }*/
//          赋予角色
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            System.out.println(role.getKeyword());
//            赋予权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new  SimpleGrantedAuthority(permission.getKeyword()));
//                list.add(permission.getKeyword());
                System.out.println(permission.getKeyword());
            }
        }
//        String encode = passwordEncoder.encode(user.getPassword());
        String encode = user.getPassword();
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,encode,list);

        return userDetails;
    }
}
